package utool

import (
	"encoding/json"
	"fmt"
	"io"
	"net"
	"net/http"
	"strings"
)

type IpResponseEntity struct {
	Query         string  `json:"query"`
	Status        string  `json:"status"`
	Continent     string  `json:"continent"`
	ContinentCode string  `json:"continentCode"`
	Country       string  `json:"country"`
	CountryCode   string  `json:"countryCode"`
	Region        string  `json:"region"`
	RegionName    string  `json:"regionName"`
	City          string  `json:"city"`
	District      string  `json:"district"`
	Zip           string  `json:"zip"`
	Lat           float64 `json:"lat"`
	Lon           float64 `json:"lon"`
	Timezone      string  `json:"timezone"`
	Offset        int     `json:"offset"`
	Currency      string  `json:"currency"`
	Isp           string  `json:"isp"`
	Org           string  `json:"org"`
	As            string  `json:"as"`
	Asname        string  `json:"asname"`
	Mobile        bool    `json:"mobile"`
	Proxy         bool    `json:"proxy"`
	Hosting       bool    `json:"hosting"`
}

func (a *App) IpSearchGo(ip string) H {
	if len(ip) == 0 {
		return M{
			"code": 0,
			"msg":  "请输入IP地址",
		}
	}

	url := fmt.Sprintf("http://ip-api.com/json/%s?lang=zh-CN", ip)
	r, err := http.Get(url)
	if err != nil {
		return M{
			"code": 0,
			"msg":  err.Error(),
		}
	}
	defer r.Body.Close()
	b, err := io.ReadAll(r.Body)
	if err != nil {
		return M{
			"code": 0,
			"msg":  err.Error(),
		}
	}

	var entityIp IpResponseEntity

	err = json.Unmarshal(b, &entityIp)
	if err != nil {
		return M{
			"code": 0,
			"msg":  err.Error(),
		}
	}
	return M{
		"code": 1,
		"msg":  "success",
		"data": entityIp,
	}
}


func (a *App) GetPublicIpGo() H {
	r, err := http.Get("http://ipinfo.io/ip")
	if err != nil {
		return M{
			"code": 0,
			"msg":  err.Error(),
		}
	}
	defer r.Body.Close()
	b, err := io.ReadAll(r.Body)
	if err != nil {
		return M{
			"code": 0,
			"msg":  err.Error(),
		}
	}
	return M{
		"code": 1,
		"msg":  "success",
		"data": string(b),
	}
}

func (a *App) GetLocalIpGo() H {
	c, _ := net.Dial("udp", "114.114.114.114:80")
	defer c.Close()
	s := c.LocalAddr().String()
	i := strings.LastIndex(s, ":")
	return M{
		"code": 1,
		"msg":  "success",
		"data": s[0:i],
	}
}
